//
//  IDCardFaceIDVC.m
//  Peso Guide
//
//  Created by macbook on 2025/6/13.
//

#import "IDCardFaceIDVC.h"
#import "IDCardExampleVC.h"
#import "FaceIDExampleVC.h"
#import "InformationAlertView.h"
#import "UIButton+WebCache.h"
#import "ProductDetailViewController.h"
#import "IdentityInfomationVC.h"

@interface IDCardFaceIDVC ()

@property (nonatomic, strong) UIView *whiteView;
@property (nonatomic, strong) UILabel *idCardLabel;
@property (nonatomic, strong) UILabel *faceIdLabel;
@property (nonatomic, strong) UIButton *idCardImg;
@property (nonatomic, strong) UIButton *faceIdImg;
@property (nonatomic, strong) UIButton *idCardUpLoadButton;
@property (nonatomic, strong) UIButton *faceIdUpLoadButton;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) NSMutableArray *userInfoRequestArr;

@end

@implementation IDCardFaceIDVC

- (void)upLoadIDCard:(NSDictionary *)chooseIDCardImgDic chooseType:(NSString *)chooseType {
    self.chooseIDCardImgDic = chooseIDCardImgDic;
    self.chooseType = chooseType;
    
    UIImage *img = [self.chooseIDCardImgDic safeObjectForKey:@"img"];
    NSData *imgData = [self.chooseIDCardImgDic safeObjectForKey:@"imgData"];
    NSString *inconvenient = [NSString stringWithFormat:@"%@",[self.chooseIDCardImgDic safeObjectForKey:@"inconvenient"]];
    
    NSDictionary *params = @{@"inconvenient":inconvenient,@"unboundlocalerror":@"11",@"consisting":self.chooseType};
    
    [SVProgressHUD show];
    
    [AWHttpService uploadImage:imgData params:params imageName:[NSString stringWithFormat:@"Id_photo_front_%@",self.chooseType] completion:^(NSData *data, NSURLResponse *response, NSError *error) {
        [SVProgressHUD dismiss];

        if (error) {
            DLog(@"error: %@", error.localizedDescription);
            return;
        }
        
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        
        if (httpResponse.statusCode == 200) {
            
            NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSDictionary *responseObject = [AppTools dictionaryWithJsonString:result];
            
            if (SUCCESS) {
                // 解析服务器响应（如果需要）
                DLog(@"responseObject------- %@", responseObject);
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSDictionary *associating = [NSDictionary safeDictionaryWithDictionary:[responseObject safeObjectForKey:@"associating"]];
                    self.userInfoRequestArr = [NSMutableArray safeArrayWithArray:[associating safeObjectForKey:@"tree"]];
                    
                    WeakSelf;
                    InformationAlertView *alertView = [[InformationAlertView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) data:self.userInfoRequestArr];
                    alertView.chooseIdHandler = ^(BOOL isCanUse) {
                        if (isCanUse == YES) {
                            [self loadIDFACE];
                            [weakSelf.idCardUpLoadButton setBackgroundImage:[UIImage imageNamed:@"ic_identity_success"] forState:0];
                            [weakSelf.idCardImg setBackgroundImage:img forState:0];
                            
                        }else {
                            weakSelf.chooseIDCardImgDic = [NSMutableDictionary dictionaryWithCapacity:0];
                            [weakSelf.idCardUpLoadButton setBackgroundImage:[UIImage imageNamed:@"ic_identity_upload"] forState:0];
                            [weakSelf.idCardImg setBackgroundImage:[UIImage imageNamed:@"ic_identity_id_card"] forState:0];
                            
                        }
                    };
                    alertView.dataDic = associating;
                    alertView.cardType = self.chooseType;
                    [self.view addSubview:alertView];
                });
                
            }else {
                NSString *order = [NSString stringWithFormat:@"%@",[responseObject safeObjectForKey:@"order"]];
                [SVProgressHUD showErrorWithStatus:order];
                [SVProgressHUD dismissWithDelay:3.0f];

            }
            
        } else {
            NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSDictionary *responseObject = [AppTools dictionaryWithJsonString:result];
            NSString *order = [NSString stringWithFormat:@"%@",[responseObject safeObjectForKey:@"order"]];
            [SVProgressHUD showErrorWithStatus:order];
            [SVProgressHUD dismissWithDelay:3.0f];

        }
    }];
}

- (void)upLoadFaceCard:(NSDictionary *)chooseFaceIDImgDic {
    self.chooseFaceIDImgDic = chooseFaceIDImgDic;

    UIImage *img = [self.chooseFaceIDImgDic safeObjectForKey:@"img"];
    NSData *imgData = [self.chooseFaceIDImgDic safeObjectForKey:@"imgData"];
    NSString *inconvenient = [NSString stringWithFormat:@"%@",[self.chooseIDCardImgDic safeObjectForKey:@"inconvenient"]];
    
    NSDictionary *params = @{@"inconvenient":inconvenient,@"unboundlocalerror":@"10",@"consisting":@""};
    
    [SVProgressHUD show];
    
    [AWHttpService uploadImage:imgData params:params imageName:@"Face_Id_photo" completion:^(NSData *data, NSURLResponse *response, NSError *error) {
        [SVProgressHUD dismiss];

        if (error) {
            DLog(@"error: %@", error.localizedDescription);
            return;
        }
        
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        
        if (httpResponse.statusCode == 200) {
            
            NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSDictionary *responseObject = [AppTools dictionaryWithJsonString:result];
            
            if (SUCCESS) {
                [self loadIDFACE];
                // 解析服务器响应（如果需要）
                DLog(@"responseObject------- %@", responseObject);
                
                NSString *startTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"upLogType-4-startTime"];
                NSString *lat = [[NSUserDefaults standardUserDefaults] objectForKey:@"upLogType-4-lat"];
                NSString *lng = [[NSUserDefaults standardUserDefaults] objectForKey:@"upLogType-4-lng"];

                NSString *endTime = [DataPointManager getCurrentTimestamp];
                
                [[DataPointManager sharedManager] senRequestWithType:@"4" startTime:startTime endTime:endTime lng:lng lat:lat orderId:@""];
//                [[DataPointManager sharedManager] logEventWithType:@"4" startTime:startTime endTime:endTime orderId:@""];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.faceIdUpLoadButton setBackgroundImage:[UIImage imageNamed:@"ic_identity_success"] forState:0];
                    [self.faceIdImg setBackgroundImage:img forState:0];
                });
                
            }else {
                NSString *order = [NSString stringWithFormat:@"%@",[responseObject safeObjectForKey:@"order"]];
                [SVProgressHUD showErrorWithStatus:order];
                [SVProgressHUD dismissWithDelay:3.0f];

            }
            
        } else {
            NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSDictionary *responseObject = [AppTools dictionaryWithJsonString:result];
            NSString *order = [NSString stringWithFormat:@"%@",[responseObject safeObjectForKey:@"order"]];
            [SVProgressHUD showErrorWithStatus:order];
            [SVProgressHUD dismissWithDelay:3.0f];

        }
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navView.backgroundColor = ColorHex(@"#1A7A35");
    self.titleLabel.text = [Lang set:@"Identity information"];
    self.backColor = ColorHex(@"#F3F4F8");

    
    UIImageView *topImg = [PesoKit createImageViewWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenWidth*0.736) imageNamed:@"ic_identity_top_img"];
    [self.view addSubview:topImg];
    
    UILabel *topLabel = [PesoKit createLabelWithFrame:CGRectMake(154, kStarBarHeight, KScreenWidth-154-20, 91) backGroundColor:[UIColor clearColor] text:[Lang set:@"Please fill in your personal data (don't worry,your information and data are protected)"] textColor:ColorHex(@"#0E1D31") font:FONT(FontWeightStyleRegular, 12)];
    topLabel.numberOfLines = 0;
    [topImg addSubview:topLabel];
    
    _whiteView = [PesoKit createViewWithFrame:CGRectMake(0, kStarBarHeight+topImg.height*0.33, KScreenWidth, KScreenHeight) backGroundColor:ColorHex(@"#FFFFFF")];
    _whiteView.clipsToBounds = YES;
    _whiteView.layer.cornerRadius = 15.0f;
    [self.view addSubview:_whiteView];
    
    _idCardLabel = [PesoKit createLabelWithFrame:CGRectMake(24, 20, KScreenWidth-40, 22) backGroundColor:ColorHex(@"#FFFFFF") text:[Lang set:@"Front of lD photo"] textColor:ColorHex(@"#0E1D31") font:FONT(FontWeightStyleMedium, 16)];
    [_whiteView addSubview:_idCardLabel];
    
    _idCardImg = [[UIButton alloc] initWithFrame:CGRectMake(24, 62, 220, 136)];
    [_idCardImg setBackgroundImage:[UIImage imageNamed:@"ic_identity_id_card"] forState:0];
    [_idCardImg addTarget:self action:@selector(idCardUpLoadButtonClick) forControlEvents:UIControlEventTouchUpInside];
    _idCardImg.clipsToBounds = YES;
    _idCardImg.layer.cornerRadius = 16.0f;
    _idCardImg.contentMode = UIViewContentModeScaleAspectFill;
    [_whiteView addSubview:_idCardImg];
    
    _idCardUpLoadButton = [[UIButton alloc] initWithFrame:CGRectMake(_idCardImg.right+42, 104, 32, 32)];
    [_idCardUpLoadButton setBackgroundImage:[UIImage imageNamed:@"ic_identity_upload"] forState:0];
    [_idCardUpLoadButton addTarget:self action:@selector(idCardUpLoadButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [_whiteView addSubview:_idCardUpLoadButton];
    
    _faceIdLabel = [PesoKit createLabelWithFrame:CGRectMake(24, 222, KScreenWidth-40, 22) backGroundColor:ColorHex(@"#FFFFFF") text:[Lang set:@"Face recognition"] textColor:ColorHex(@"#0E1D31") font:FONT(FontWeightStyleMedium, 16)];
    [_whiteView addSubview:_faceIdLabel];
    
    _faceIdImg = [[UIButton alloc] initWithFrame:CGRectMake(24, 264, 220, 136)];
    [_faceIdImg setBackgroundImage:[UIImage imageNamed:@"ic_identity_face_id"] forState:0];
    [_faceIdImg addTarget:self action:@selector(faceIdUpLoadButtonClick) forControlEvents:UIControlEventTouchUpInside];
    _faceIdImg.clipsToBounds = YES;
    _faceIdImg.layer.cornerRadius = 16.0f;
    _faceIdImg.contentMode = UIViewContentModeScaleAspectFill;
    [_whiteView addSubview:_faceIdImg];
    
    _faceIdUpLoadButton = [[UIButton alloc] initWithFrame:CGRectMake(_faceIdImg.right+42, 300, 32, 32)];
    [_faceIdUpLoadButton setBackgroundImage:[UIImage imageNamed:@"ic_identity_upload"] forState:0];
    [_faceIdUpLoadButton addTarget:self action:@selector(faceIdUpLoadButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [_whiteView addSubview:_faceIdUpLoadButton];
    
    _nextButton = [PesoKit createButtonWithFrame:CGRectMake((KScreenWidth-214)/2.0, KScreenHeight-kSafeBottomHeight-30-44, 214, 44) backGroundColor:ColorHex(@"#FE7133") title:[Lang set:@"Next"] titleColor:ColorHex(@"#FFFFFF") font:FONT(FontWeightStyleMedium, 18)];
    _nextButton.clipsToBounds = YES;
    _nextButton.layer.cornerRadius = 22.0f;
    [_nextButton addTarget:self action:@selector(nextButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_nextButton];
    
    [self.view addSubview:self.navView];
    
    [self loadIDFACE];
}

- (void)loadIDFACE {
    [[AWHttpService service] postWithUrl:@"/trains/imports" params:@{@"across":self.productId} succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
            NSDictionary *dataDic = [NSDictionary safeDictionaryWithDictionary:[responseObject safeObjectForKey:@"associating"]];
            self.normallyDic = [NSDictionary safeDictionaryWithDictionary:[dataDic safeObjectForKey:@"normally"]];
            self.prefixDic = [NSDictionary safeDictionaryWithDictionary:[dataDic safeObjectForKey:@"prefix"]];
            
            // 身份证正面
            //状态 0未完成 1已完成
            NSString *idPackages = [self.normallyDic safeObjectForKey:@"packages"];
            NSString *idRecent = [self.normallyDic safeObjectForKey:@"recent"];
            //活体照片
            //状态 0未完成 1已完成
            NSString *facePackages = [self.prefixDic safeObjectForKey:@"packages"];
            NSString *faceRecent = [self.prefixDic safeObjectForKey:@"recent"];
            
            if (idPackages.integerValue == 1) {
                self.idCardImg.userInteractionEnabled = NO;
                self.idCardUpLoadButton.userInteractionEnabled = NO;
                [self.idCardImg sd_setImageWithURL:[NSURL URLWithString:idRecent] forState:0];
                [self.idCardUpLoadButton setBackgroundImage:[UIImage imageNamed:@"ic_identity_success"] forState:0];
            }
            if (facePackages.integerValue == 1) {
                self.faceIdImg.userInteractionEnabled = NO;
                self.faceIdUpLoadButton.userInteractionEnabled = NO;
                [self.faceIdImg sd_setImageWithURL:[NSURL URLWithString:faceRecent] forState:0];
                [self.faceIdUpLoadButton setBackgroundImage:[UIImage imageNamed:@"ic_identity_success"] forState:0];
            }
            
        }else {
            NSString *order = [NSString stringWithFormat:@"%@",[responseObject safeObjectForKey:@"order"]];
            [SVProgressHUD showErrorWithStatus:order];
            [SVProgressHUD dismissWithDelay:3.0f];
        }
    } fail:^(NSInteger errorType, id  _Nonnull error) {
        
    }];
}

- (void)idCardUpLoadButtonClick {
    IdentityInfomationVC *vc = [[IdentityInfomationVC alloc] init];
    vc.productId = self.productId;
    vc.idCardFaceIDVC = self;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)faceIdUpLoadButtonClick {
    NSString *idPackages = [NSString stringWithFormat:@"%@",[self.normallyDic safeObjectForKey:@"packages"]];

    if ((self.chooseIDCardImgDic == nil || self.chooseIDCardImgDic.allKeys == 0) && idPackages.integerValue == 0) {
        [SVProgressHUD showErrorWithStatus:[Lang set:@"Please upload your ID photo first"]];
        [SVProgressHUD dismissWithDelay:3.0f];

        return;
    }
    FaceIDExampleVC *vc = [[FaceIDExampleVC alloc] init];
    vc.idCardFaceIDVC = self;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)nextButtonClick {
    NSString *idPackages = [NSString stringWithFormat:@"%@",[self.normallyDic safeObjectForKey:@"packages"]];
    NSString *facePackages = [NSString stringWithFormat:@"%@",[self.prefixDic safeObjectForKey:@"packages"]];

    if ((self.chooseIDCardImgDic != nil && self.chooseIDCardImgDic.allKeys > 0) || idPackages.integerValue == 1) {
        //身份认证完成 去人脸
        if ((self.chooseFaceIDImgDic != nil && self.chooseFaceIDImgDic.allKeys > 0) || facePackages.integerValue == 1) {
            
        }else {
            FaceIDExampleVC *vc = [[FaceIDExampleVC alloc] init];
            vc.idCardFaceIDVC = self;
            [self.navigationController pushViewController:vc animated:YES];
            return;
        }
    }else {
        IdentityInfomationVC *vc = [[IdentityInfomationVC alloc] init];
        vc.productId = self.productId;
        vc.idCardFaceIDVC = self;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    if (self.chooseIDCardImgDic != nil && self.chooseIDCardImgDic.allKeys > 0 &&
        self.chooseFaceIDImgDic != nil && self.chooseFaceIDImgDic.allKeys > 0) {
        
        for (int i = 0; i < [AppTools getCurrentVC].navigationController.viewControllers.count; i++) {
            UIViewController *vc = [[AppTools getCurrentVC].navigationController.viewControllers safeObjectAtIndex:i];
            if ([vc isKindOfClass:[ProductDetailViewController class]]) {
                [[AppTools getCurrentVC].navigationController popToViewController:vc animated:YES];
                return;
            }
            [[AppTools getCurrentVC].navigationController popViewControllerAnimated:YES];
        }
    }else {
        // 身份证正面
        //状态 0未完成 1已完成
        NSString *idPackages = [self.normallyDic safeObjectForKey:@"packages"];
        //活体照片
        //状态 0未完成 1已完成
        NSString *facePackages = [self.prefixDic safeObjectForKey:@"packages"];
        
        if (facePackages.integerValue == 1 || idPackages.integerValue == 1) {
            for (int i = 0; i < [AppTools getCurrentVC].navigationController.viewControllers.count; i++) {
                UIViewController *vc = [[AppTools getCurrentVC].navigationController.viewControllers safeObjectAtIndex:i];
                if ([vc isKindOfClass:[ProductDetailViewController class]]) {
                    [[AppTools getCurrentVC].navigationController popToViewController:vc animated:YES];
                    return;
                }
                [[AppTools getCurrentVC].navigationController popViewControllerAnimated:YES];
            }
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
